<template>
  <div
    v-if="lotteryInfo"
    class="luck-wrap"
  >
    <div
      v-if="lotteryInfo.actName"
      class="title"
    >
      {{ lotteryInfo.actName }}
    </div>
    <div
      v-if="lotteryInfo.description"
      class="desc"
    >
      {{ lotteryInfo.description }}
    </div>
    <LuckyWheel
      ref="myLuckyRef"
      :blocks="blocks"
      :buttons="buttons"
      :prizes="prizes"
      height="300px"
      width="300px"
      @end="endCallback"
      @start="startCallback"
    />
    <div
      v-if="myPrizes"
      class="my-prizes-wrap"
    >
      <img
        v-if="myPrizes.image"
        :src="myPrizes.image"
        alt=""
      />
      <div class="mt10">{{ $t("form.lottery.congratulations") }}{{ myPrizes.name }}</div>
      <div
        class="mt10"
        v-html="lotteryInfo.extraInfo?.claimInfo"
      ></div>
      <div
        v-if="lotteryInfo.rewardType == 1 && !showHistory"
        class="redeem-code-container"
      >
        <div class="redeem-code-text">
          {{ myPrizes.code }}
        </div>
        <div class="redeem-code-hint">{{ $t("form.lottery.instruction1") }}</div>
      </div>
      <el-form
        v-if="lotteryInfo.rewardType == 2 && !showHistory"
        :model="form"
        class="mt20"
        label-position="left"
        label-width="70px"
        size="small"
        ref="infoFormRef"
        :rules="rules"
      >
        <el-form-item
          :label="$t('form.lottery.username')"
          prop="name"
        >
          <el-input
            v-model="form.name"
            :placeholder="$t('form.lottery.enterName')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('form.lottery.phoneNumber')"
          prop="phone"
        >
          <el-input
            v-model="form.phone"
            :placeholder="$t('form.lottery.enterPhoneNumber')"
          />
        </el-form-item>
        <el-form-item :label="$t('form.lottery.address')">
          <el-input
            v-model="form.address"
            :placeholder="$t('form.lottery.enterAddress')"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSubmit"
          >
            {{ $t("form.lottery.submit") }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import {
  DrawActivities,
  DrawPrizesVO,
  getActivitiesByTimeRange,
  startLottery,
  updateParticipantInfo
} from "@/api/project/lottery";
import { useRoute } from "vue-router";
import { LuckyWheel } from "@lucky-canvas/vue";
import { MessageUtil } from "@/utils/messageUtil";
import { i18n } from "@/i18n";
import { Local } from "@/utils/storage";
import { FormRules } from "element-plus";

const route = useRoute();

const lotteryInfo = ref<DrawActivities | null>(null);

const sourceType = "FORM_LOTTERY";

const form = reactive({
  name: "",
  phone: "",
  address: ""
});

const infoFormRef = ref<any>(null);

const cacheKey = "lotteryInfo" + route.query.id;

const showHistory = ref(false);

const handleSubmit = async () => {
  await infoFormRef.value.validate((valid, fields) => {
    if (valid) {
      updateParticipantInfo({
        id: lotteryInfo?.value?.id as number,
        name: form.name,
        phone: form.phone,
        address: form.address
      }).then(() => {
        MessageUtil.success(i18n.global.t("common.saveSuccess"));
        showHistory.value = true;
      });
    } else {
    }
  });
};

const rules = reactive<FormRules<any>>({
  name: [{ required: true, message: i18n.global.t("form.lottery.enterName"), trigger: "blur" }],
  phone: [{ required: true, message: i18n.global.t("form.lottery.enterPhoneNumber"), trigger: "blur" }]
});

onMounted(async () => {
  const res = await getActivitiesByTimeRange(sourceType, route.query.key as string);
  lotteryInfo.value = res.data;
  let arr = [];
  if (lotteryInfo.value!.drawPrizesVoList) {
    for (let i = 0; i < lotteryInfo.value!.drawPrizesVoList.length; i++) {
      let item = lotteryInfo.value!.drawPrizesVoList[i];
      arr.push({
        id: item.id,
        imgs: [
          {
            width: "30px",
            height: "30px",
            top: "30",
            src:
              item.image ||
              ""
          }
        ],
        fonts: [{ text: item.name, top: "10%", fontSize: "11px" }]
      });
    }

    if (arr.length < 9) {
      arr = fillDefaultPrizes(arr);
    }
    // 设置斑马颜色
    arr = arr.map((item, index) => {
      if (index % 2 === 0) {
        item.background = "#F8DEF8";
      } else {
        item.background = "#fdebed";
      }
      return item;
    });
    prizes.value = arr;
  }
  if (Local.get(cacheKey)) {
    showHistory.value = true;
    myPrizes.value = Local.get(cacheKey);
  }
});

const defaultPrize = {
  imgs: [
    {
      width: "30px",
      height: "30px",
      top: "30",
      src: ""
    }
  ],
  fonts: [{ text: i18n.global.t("form.lottery.thankYou"), top: "10%", fontSize: "12px" }]
};
/**
 * 填充默认奖励
 */
const fillDefaultPrizes = (arr: any[]) => {
  const targetLength = 9;
  let indexToInsert = 1;
  while (arr.length < targetLength) {
    arr.splice(indexToInsert, 0, { ...defaultPrize });
    indexToInsert = indexToInsert + 2;
  }
  return arr;
};

const blocks = [
  {
    padding: "28px",
    imgs: [
      {
        src: "",
        width: "100%",
        height: "100%"
      }
    ]
  }
];

const prizes = ref<any[]>([]);

const buttons = [
  {
    radius: "45%",
    pointer: true,
    imgs: [
      {
        src: "",
        width: "80%",
        top: "-100%"
      }
    ]
  }
];

// 获得的奖励
const myPrizes = ref<DrawPrizesVO | null>(null);

const myLuckyRef = ref<any>(null);
const startCallback = () => {
  if (showHistory.value) {
    MessageUtil.warning(i18n.global.t("form.lottery.alreadyParticipated"));
    return;
  }

  startLottery({
    sourceType: sourceType,
    sourceId: route.query.key as string,
    drawActivitiesId: lotteryInfo?.value?.id as number,
    dataId: route.query.id as string
  })
    .then(res => {
      // 调用抽奖组件的play方法开始游戏
      myLuckyRef.value.play();
      setTimeout(() => {
        let index = null;
        if (!res.data) {
          // 找到没有id的
          index = prizes.value.findIndex(item => !item.id);
        } else {
          index = prizes.value.findIndex(item => item.id == res.data.id);
        }
        // 调用stop停止旋转并传递中奖索引
        myLuckyRef.value.stop(index);
        setTimeout(() => {
          if (res.data) {
            myPrizes.value = res.data;
            Local.set(cacheKey, res.data);
          }
        }, 2000);
      }, 2200);
    })
    .catch();
};

// 抽奖结束会触发end回调
const endCallback = (prize: any) => {
  console.log(prize);
};
</script>
<style lang="scss" scoped>
.luck-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
  height: 100%;

  .title {
    font-size: var(--el-font-size-medium);
    line-height: 40px;
    color: var(--el-text-color-primary);
  }

  .desc {
    font-size: var(--el-font-size-base);
    color: var(--el-text-color-placeholder);
  }
}

.my-prizes-wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-top: 10px;

  img {
    max-width: 60%;
  }

  .redeem-code-container {
    margin-top: 10px;
    background-color: var(--el-color-primary-light-8);
    padding: 20px;
    border-radius: 5px;
    text-align: center;
    position: relative;
    overflow: hidden;
  }

  /* 锯齿尺伪元素样式 */
  .redeem-code-container::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    height: 100%;
    background: linear-gradient(to bottom, #333 50%, transparent 50%); /* 条形的颜色和高度分布 */
  }

  /* 兑奖码文本样式 */
  .redeem-code-text {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
  }

  /* 提示文本样式 */
  .redeem-code-hint {
    font-size: 14px;
    color: #666;
  }
}
</style>
